#!python3.3
"""
Setup a basic pylast environment to simplify testing.
"""
import os
import pylast
import pynoisebot

json_decoder = pynoisebot.json_decoder

default_lastfm_conf_dir = os.path.join(os.getcwd(), 'data')
default_lastfm_conf_file = 'lastfm.json'

with open(os.path.join(default_lastfm_conf_dir, default_lastfm_conf_file)) as conf_file:
	config = json_decoder.decode(conf_file.read())

api_key = config['apikey']
api_secret = config['apisecret']
username = config['username']
password_hash = pylast.md5(config['userpass'])

if api_secret and username and password_hash:
	user_can_authenticate = True
else:
	user_can_authenticate = False

def get_lastfm_network(api_key, api_secret, username, password_hash):
	return pylast.LastFMNetwork(api_key=api_key, api_secret=api_secret, username=username, password_hash=password_hash)

try:
	network = get_lastfm_network(api_key, api_secret, username, password_hash)
except pylast.WSError as exc:
	error_code = int(exc.get_id())
	if error_code in (4, 13):
		network = get_lastfm_network(api_key, api_secret=None, username=None, password_hash=None)
	else:
		raise